package com.samsung.booksmanagement;

import java.util.Calendar;
import java.util.GregorianCalendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

public class SetSchedule {

	private AlarmManager mAlarm;

	private AlarmReceive mReceive;

	private PendingIntent mPending;

	private Context mContext;

	DatabaseSevice mDatabaseService;

	public static String BOOK_NAME = "name_book";

	public SetSchedule(Context context, DatabaseSevice service) {
		mAlarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		mReceive = new AlarmReceive();
		context.registerReceiver(mReceive,
				new IntentFilter("com.samsung.alarm"));

		this.mDatabaseService = service;
		mContext = context;
	}

	public void setOn(Calendar calender, int idBook, String bookName) {
		long timeSet = calender.getTimeInMillis();
		long timeCurrent = new GregorianCalendar().getTimeInMillis();
		long scheduleTime = 0;

		if (timeSet > timeCurrent) {
			scheduleTime = timeSet;
		} else {
			scheduleTime = AlarmManager.INTERVAL_HALF_DAY * 2
					- Math.abs(timeCurrent - timeSet);
		}

		Intent intent = new Intent("com.samsung.alarm");
		intent.putExtra(BOOK_NAME, bookName);

		mPending = PendingIntent.getBroadcast(mContext, idBook, intent,
				PendingIntent.FLAG_UPDATE_CURRENT);

		mAlarm.setRepeating(AlarmManager.RTC_WAKEUP, scheduleTime,
				AlarmManager.INTERVAL_DAY, mPending);

		Schedule schedule = new Schedule();
		schedule.setBookId(idBook);
		schedule.setSchedule(1);
		schedule.setTime(String.valueOf(scheduleTime));
		mDatabaseService.addSchedule(schedule);
	}

	public void setOff(int idBook) {
		Intent intent = new Intent("com.samsung.alarm");

		int idAlarm = mDatabaseService.getIdScheduleByBookId(idBook);
		if (idAlarm != -1) {
			mPending = PendingIntent.getBroadcast(mContext, idAlarm, intent,
					PendingIntent.FLAG_UPDATE_CURRENT);

			mAlarm.cancel(mPending);
		}
		mContext.unregisterReceiver(mReceive);
	}
}
